<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    width="700px"
    style="width: 700px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '84px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="操作选择" prop="target">
            <!-- <BaseSelect
              v-model="formData.ingredientType"
              :options="cascaderOptions"
              placeholder="操作选择"
            /> -->
            <el-cascader
              ref="refCascader"
              v-model.number="formData.target"
              :options="cascaderOptions"
              :props="cascaderProps"
              style="width: 100%"
              filterable
              clearable
              @change="handleCascaderChange"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col v-if="formData.ingredientType === 'flavour'" :span="24">
          <el-form-item label="选择调料" prop="target">
            <BaseSelect
              v-model.number="formData.target"
              :options="selectOptions"
              label="调料"
              filterable
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item prop="timeOffset" label="步骤时长">
            <TextInput
              v-model.number="formData.timeOffset"
              label="步骤时长"
              verify-type="nzint"
              maxlength="10"
            >
              <template #append>
                <span>秒/s</span>
              </template>
            </TextInput>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="formData.ingredientType === 'flavour'">
          <el-form-item prop="goal" label="投放数量">
            <TextInput
              v-model.number="formData.goal"
              label="投放数量"
              verify-type="nzint"
              maxlength="10"
            >
              <template #append>
                <span>{{
                  ingredientValue === 'liquid' ? '毫升/ml' : '克/g'
                }}</span>
              </template>
            </TextInput>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="formData.ingredientType === 'material'">
          <el-form-item prop="turnCount" label="翻倒次数">
            <TextInput
              v-model.number="formData.turnCount"
              label="翻倒次数"
              verify-type="nzint"
              maxlength="1"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24" v-if="formData.ingredientType === 'shovel'">
          <el-form-item prop="goal" label="旋转方式">
            <BaseSelect
              v-model.number="formData.type"
              :options="g_options.weightUnitOptions"
              label="旋转方式"
            />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="24" v-if="formData.ingredientType === 'heater'">
          <el-form-item prop="goal" label="功率等级">
            <BaseSelect
              v-model.number="formData.type"
              :options="g_options.weightUnitOptions"
              label="功率等级"
            />
          </el-form-item>
        </el-col> -->
        <el-col v-if="formData.ingredientType === 'material'" :span="24">
          <el-form-item style="margin-bottom: 0" required>
            <template #label>
              <label>食材盒{{ props.ingredientIndex }}</label>
            </template>
            <el-button
              type="primary"
              style="margin-bottom: 10px"
              @click="handleAddIngredient"
              >添加食材</el-button
            >
          </el-form-item>
        </el-col>
        <el-col v-if="formData.ingredientType === 'material'" :span="24">
          <el-form-item
            label-width="0"
            class="form-item-table"
            prop="materialList"
          >
            <BaseTable
              ref="refContentTable"
              v-loading="tableLoading"
              :data="formData.materialList"
              row-key="id"
            >
              <TableColumn
                prop="ingredientName"
                label="食材名称"
                :column-width="columnWidthObj.ingredientName"
              />
              <TableColumn
                prop="goal"
                label="所需用量"
                :column-width="columnWidthObj.goal"
              />
              <TableColumn
                prop="processId"
                label="加工方式"
                :column-width="columnWidthObj.processId"
              >
                <template #default="{ row }">
                  <span
                    :class="
                      g_options.getOptionText(processList, row.processId, '--')
                    "
                    >{{
                      g_options.getOptionText(processList, row.processId, '--')
                    }}</span
                  >
                </template>
              </TableColumn>
              <TableColumn
                prop="action"
                fixed="right"
                :label="$t('public.action')"
                :column-width="columnWidthObj.action"
              >
                <template #default="{ row, $index }">
                  <el-button text @click="handleIngredientEdit(row, $index)">
                    {{ $t('public.edit') }}
                  </el-button>
                  <el-button
                    text
                    @click="handleIngredientDelete(row, $index)"
                    >{{ $t('public.delete') }}</el-button
                  >
                </template>
              </TableColumn>
            </BaseTable>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>
  <AddIngredient
    v-if="addIngredientVisible"
    v-model="addIngredientVisible"
    :type="addOrEditType"
    :options="ingredientOptions"
    :row="ingredientRow"
    @add="handleAddIngredientCb"
    @update="handleUpdateIngredientCb"
  />
</template>

<script setup>
import AddIngredient from './AddIngredient.vue'

const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  id: {
    type: String,
    default: ''
  },
  row: {
    type: Object,
    default: () => {}
  },
  stepList: {
    type: Array,
    default: () => []
  },
  ingredientIndex: {
    type: Number,
    default: () => 1
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() => (props.type === 'add' ? '步骤新建' : '步骤修改'))

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  name: '',
  ingredientType: '', // 最外层大类的value值
  ingredientName: '', // 最里层的label值
  target: '', // 最里层的value值
  turnCount: '',
  goal: '',
  timeOffset: '',
  // boxName: '',
  // boxTag: '',
  // num: '',
  // processId: '',
  materialList: []
})
const rules = ref({
  target: g_rules.selectRule('操作选择'),
  turnCount: g_rules.turnCount,
  goal: g_rules.commonInputText('投放数量'),
  timeOffset: g_rules.commonInputText('步骤时长')
})
const processList = ref([])
const refCascader = ref(null)
const cascaderOptions = ref([])
const cascaderProps = ref({
  children: 'ingredientList'
})
const ingredientValue = ref('')
const refContentTable = ref(null)
const tableLoading = ref(false)
const columnWidthObj = ref({})
// 弹框参数
const addIngredientVisible = ref(false)
const ingredientOptions = ref([])
const ingredientRow = ref({})
const addOrEditType = ref('')
const ingredientTableIndex = ref('')

onMounted(() => {
  getDropList()
  if (props.type === 'edit') {
    g_utils.assignFormData(formData.value, props.row)
    if (props.row.ingredientType === 'material') {
      formData.value.target = props.row.ingredientType
      formData.value.materialList = props.row.materialList
    } else {
      formData.value.target = props.row.target
    }
    console.log('formData.value', formData.value)
  }
  getIngredientList()
})

const getIngredientList = _ => {
  g_api.recipe.apiRecipeQueryIngredientList().then(({ code, data }) => {
    if (code === '200' && data) {
      ingredientOptions.value =
        data.find(item => item.value === 'material')?.ingredientList || []
      cascaderOptions.value = g_.cloneDeep(data).filter(item => {
        if (props.ingredientIndex > 4 && item.value === 'material') {
          return false
        }
        if (item.value === 'material') item.ingredientList = []
        return true
      })
      const values = findAllValues(data, formData.value.target)
      const pathValues = values?.pathValues || []
      formData.value.ingredientType = pathValues[0] || ''
      ingredientValue.value = pathValues[pathValues.length - 2] || ''
    }
  })
}

const getDropList = () => {
  g_api.foodstuff.apiProcessDropList().then(({ code, data }) => {
    if (code === '200' && data) {
      processList.value = data.map(item => ({
        ...item,
        value: item.id,
        label: item.name
      }))
    }
  })
}

/**
 * 根据target匹配ingredientType的值
 * @param obj
 * @param target
 */
const findAllValues = (obj, target, pathValues = []) => {
  for (let key in obj) {
    if (obj[key] === target) {
      return {
        ...obj,
        pathValues: [...pathValues, obj[key]]
      }
    }

    if (
      typeof obj[key] === 'object' &&
      obj[key] !== null &&
      Object.keys(obj[key]).length
    ) {
      const found = findAllValues(
        obj[key],
        target,
        obj.value ? [...pathValues, obj.value] : pathValues
      )
      if (found) return found
    }
  }
  return ''
}

const handleClose = _ => {
  dialogVisible.value = false
}

const handleCascaderChange = (e, a, b, c) => {
  const checkedNode = refCascader.value.getCheckedNodes()[0]
  console.log('handleCascaderChange', e, checkedNode)
  const pathValues = checkedNode?.pathValues || []
  formData.value.ingredientType = e?.length ? e[0] : ''
  formData.value.ingredientName = checkedNode?.label || ''
  formData.value.target = checkedNode?.value || ''
  ingredientValue.value = pathValues[pathValues.length - 2] || ''
  // 设置初始值
  formData.value.turnCount = ''
  formData.value.materialList = []
  if (formData.value.ingredientType === 'material') {
    formData.value.turnCount = 1
  }
  if (formData.value.ingredientType !== 'flavour') {
    formData.value.goal = ''
  }
}

const handleAddIngredient = _ => {
  addOrEditType.value = 'add'
  addIngredientVisible.value = true
}

const handleIngredientEdit = (row, i) => {
  ingredientRow.value = row
  addOrEditType.value = 'edit'
  ingredientTableIndex.value = i
  addIngredientVisible.value = true
}

const handleIngredientDelete = (row, i) => {
  ElMessageBox.confirm(`是否删除该食材【${row.name}】?`, g_t('public.tip'), {
    confirmButtonText: g_t('public.confirm'),
    cancelButtonText: g_t('public.cancel'),
    type: 'warning'
  })
    .then(() => {
      formData.value.materialList.splice(i, 1)
    })
    .catch(() => {})
}

const handleAddIngredientCb = data => {
  formData.value.materialList = [...formData.value.materialList, data]
}

const handleUpdateIngredientCb = data => {
  formData.value.materialList.splice(ingredientTableIndex.value, 1, data)
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    const getLabel = value => {
      return (
        cascaderOptions.value.find(item => item.value === value)?.label || ''
      )
    }
    switch (formData.value.ingredientType) {
      // 食材
      case 'material':
        // formData.value.materialList.forEach(item => {
        //   item.name =
        //     item.ingredientName +
        //     item.goal +
        //     '克，翻倒' +
        //     formData.value.turnCount +
        //     '次'
        // })
        formData.value.name =
          formData.value.materialList
            .map(item => item.ingredientName + item.goal + '克')
            .join('，') +
          '，翻倒' +
          formData.value.turnCount +
          '次'
        const ingredientData = formData.value.materialList[0]
        formData.value.ingredientName = ingredientData.ingredientName
        formData.value.goal = ingredientData.goal
        formData.value.target = ingredientData.target
        break
      // 调料
      case 'flavour':
        formData.value.name =
          formData.value.ingredientName + formData.value.goal + '克'
        break
      default:
        formData.value.name =
          getLabel(formData.value.ingredientType) +
          formData.value.ingredientName
        break
    }
    console.log('formData.value', formData.value)
    emit(props.type === 'add' ? 'add' : 'update', formData.value)
    handleClose()
  })
}
</script>

<style scoped lang="scss"></style>
